package com.kangjia.config;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;

/**
 * mongo db加载配置信息
 * 
 * @author sunshulin
 *
 */
@Configuration
public class MongoConfig {

	@Value("${mongo.connectionsPerHost}")
	private int connectionsPerHost;
	@Value("${mongo.threadsAllowedToBlockForConnectionMultiplier}")
	private int threadsAllowedToBlockForConnectionMultiplier;
	@Value("${mongo.maxWaitTime}")
	private int maxWaitTime;
	@Value("${mongo.connectTimeout}")
	private int connectTimeout;
	@Value("${mongo.database}")
	private String database;
	@Value("${mongo.user}")
	private String user;
	@Value("${mongo.pass}")
	private String pass;
	@Value("${mongo.server}")
	private String server;

	@Bean
	public MongoClient mongoClient() {
		MongoClientOptions.Builder build = new MongoClientOptions.Builder();
		build.connectionsPerHost(connectionsPerHost); // 与目标数据库能够建立的最大connection数量为50
		build.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier); // 如果当前所有的connection都在使用中，则每个connection上可以有50个线程排队等待
		build.maxWaitTime(maxWaitTime);
		build.connectTimeout(connectTimeout);
		List<MongoCredential> credentialsList = new ArrayList<MongoCredential>();
		if (StringUtils.isNotBlank(user)) {
			MongoCredential credentials = MongoCredential.createCredential(user, database, pass.toCharArray());
			credentialsList.add(credentials);
		}
		MongoClientOptions options = build.build();
		String[] servers = server.split(",");
		List<ServerAddress> as = new ArrayList<>();
		for (String address : servers) {
			String[] s = address.split(":");
			ServerAddress sa = new ServerAddress(s[0], Integer.parseInt(s[1]));
			as.add(sa);
		}
		if (StringUtils.isNotBlank(user)) {
			return new MongoClient(as, credentialsList, options);
		} else {
			return new MongoClient(as, options);
		}
	}

	@Bean
	public MongoDatabase redisConfigPool(MongoClient client) {
		return client.getDatabase(database);
	}
}
